package a51qindian.com.comprehensive.activity;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.li.utils.ToastUtil;
import com.li.widget.MultipleLayout;
import com.li.widget.TopNavigationBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import a51qindian.com.comprehensive.App;
import a51qindian.com.comprehensive.R;
import a51qindian.com.comprehensive.base.QDBaseActivity;
import a51qindian.com.comprehensive.net.ObservableHelper;
import a51qindian.com.comprehensive.net.RetrofitCreator;
import a51qindian.com.comprehensive.util.SpUtil;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Author: Li
 * Date: 2017/9/29 0029
 * Description: 重置密码
 */

public class ResetPwdActivity extends QDBaseActivity {

    @BindView(R.id.top_navigation)
    TopNavigationBar mTopNavigation;
    @BindView(R.id.layout_content)
    MultipleLayout mLayoutContent;
    @BindView(R.id.et_account)
    EditText mEtAccount;
    @BindView(R.id.et_code)
    EditText mEtCode;
    @BindView(R.id.et_pwd)
    EditText mEtPwd;
    @BindView(R.id.et_pwd_a)
    EditText mEtPwdA;
    @BindView(R.id.txt_get_code)
    TextView mTxtGetCode;
    private CodeCountDownTimer mDownTimer;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_reset_pwd;
    }

    private String mSource;

    @Override
    protected void initSth() {
        super.initSth();
        mTopNavigation.setNavigationBarListener(this);
        mSource = getIntent().getStringExtra("source");
    }

    @OnClick({R.id.txt_get_code, R.id.btn_reset})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_get_code:

                getCode(mEtAccount.getText().toString());
                break;
            case R.id.btn_reset:
                reset(mEtAccount.getText().toString(), mEtCode.getText().toString(),
                        mEtPwd.getText().toString(), mEtPwdA.getText().toString());
                break;
        }
    }

    /**
     * 计时器
     */
    private class CodeCountDownTimer extends CountDownTimer {
        private CodeCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mTxtGetCode.setEnabled(false);
            String time = millisUntilFinished / 1000 + "秒后重新获取";
            mTxtGetCode.setText(time);
        }

        @Override
        public void onFinish() {
            mTxtGetCode.setText("重新获取");
            mTxtGetCode.setEnabled(true);
        }
    }

    /**
     * 获取验证码
     * @param phone 电话号
     */
    private void getCode(String phone) {
        mLayoutContent.onLoadingWithContent("正在获取验证码");
        Map<String, String> map = new HashMap<>();
        map.put("mobile", phone);
        ObservableHelper.createObservable(RetrofitCreator.createService().getPhoneCode(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        mLayoutContent.onSuccess();
                        try {
                            JSONObject o = new JSONObject(s);
                            String info = o.getString("info");
                            int code=o.getInt("code");
                            if (code==1) {
                                mDownTimer = new CodeCountDownTimer(60 * 1000 + 500, 1000);
                                mDownTimer.start();
                            }
                            if (!TextUtils.isEmpty(info)) {
                                ToastUtil.showToast(ResetPwdActivity.this, info);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        ToastUtil.showToast(ResetPwdActivity.this, e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDownTimer != null) {
            mDownTimer.cancel();
        }
    }

    /**
     * 重置密码
     * @param mobile    手机号
     * @param code  验证码
     * @param pwd   密码
     * @param pwdA  再次输入的密码
     */
    private void reset(String mobile, String code, String pwd, String pwdA) {
        mLayoutContent.onLoadingWithContent("正在重置密码");
        Map<String, String> map = new HashMap<>();
        map.put("mobile", mobile);
        map.put("code", code);
        map.put("password", pwd);
        map.put("repassword", pwdA);
        ObservableHelper.createObservable(RetrofitCreator.createService().resetPwd(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        mLayoutContent.onSuccess();
                        try {
                            JSONObject o = new JSONObject(s);
                            int code = o.getInt("code");
                            if (code != 1) {
                                ToastUtil.showToast(ResetPwdActivity.this, o.getString("info"));
                                return;
                            }
                            switch (mSource) {
                                case "login":
                                    Intent result = new Intent();
                                    result.putExtra("account", mEtAccount.getText().toString());
                                    result.putExtra("pwd", mEtPwd.getText().toString());
                                    setResult(RESULT_OK, result);
                                    finish();
                                    break;
                                case "setting":
                                    Intent logoutIntent = new Intent(ResetPwdActivity.this, LoginActivity.class);
                                    logoutIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                    App.finishAll();
                                    App.clearActivity();
                                    SpUtil.clearUserInfo(ResetPwdActivity.this);
                                    startActivity(logoutIntent);
                                    finish();

                                    break;
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        ToastUtil.showToast(ResetPwdActivity.this, e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
